import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 应用基础状态
  const loading = ref(false)
  const theme = ref('light') // light | dark
  const language = ref('zh') // zh | en

  // 网络状态
  const networkType = ref('wifi')
  const isOnline = ref(true)

  // 设备信息
  const systemInfo = ref({})

  // 动作
  const setLoading = state => {
    loading.value = state
  }

  const setTheme = newTheme => {
    theme.value = newTheme
    uni.setStorageSync('theme', newTheme)
  }

  const setLanguage = lang => {
    language.value = lang
    uni.setStorageSync('language', lang)
  }

  const updateNetworkStatus = (type, online = true) => {
    networkType.value = type
    isOnline.value = online
  }

  const initSystemInfo = () => {
    try {
      const info = uni.getSystemInfoSync()
      systemInfo.value = info
    } catch (error) {
      console.error('获取系统信息失败:', error)
    }
  }

  const initAppSettings = () => {
    // 恢复保存的设置
    const savedTheme = uni.getStorageSync('theme')
    const savedLanguage = uni.getStorageSync('language')

    if (savedTheme) {
      theme.value = savedTheme
    }

    if (savedLanguage) {
      language.value = savedLanguage
    }

    // 初始化系统信息
    initSystemInfo()

    // 监听网络状态
    uni.onNetworkStatusChange(res => {
      updateNetworkStatus(res.networkType, res.isConnected)
    })
  }

  return {
    // 状态
    loading,
    theme,
    language,
    networkType,
    isOnline,
    systemInfo,

    // 动作
    setLoading,
    setTheme,
    setLanguage,
    updateNetworkStatus,
    initSystemInfo,
    initAppSettings
  }
})
